/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.support.word;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.contexts.Contexts;
import cn.easyplatform.dao.BizDao;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.lang.Times;
import cn.easyplatform.type.FieldType;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public final class ReserveWordFactory {

	private ReserveWordFactory() {
	}

	/**
	 * @param name
	 * @return
	 */
	public final static Object getReserveWord(String name) {
		if (name.equalsIgnoreCase("now"))
			return new Date();
		else if (name.equalsIgnoreCase("dt")) {
			return Times.toDay();
		} else if (name.equalsIgnoreCase("user"))
			return Contexts.getCommandContext().getUser().getId();
		else if (name.equals("SUB"))
			return getSub(false, false);
		else if (name.equals("sub"))
			return getSub(false, true);
		else if (name.equals("SUBS"))
			return getSub(true, false);
		else if (name.equals("subs"))
			return getSub(true, true);
		throw new EasyPlatformWithLabelKeyException(
				"context.reserve.word.invalid", name);
	}

	/**
	 * @param name
	 * @return
	 */
	public final static FieldDo getReserveWordAs(String name) {
		if (name.equalsIgnoreCase("now") || name.equalsIgnoreCase("dt")) {
			FieldDo fd = new FieldDo(FieldType.DATETIME);
			fd.setName(name);
			if (name.equalsIgnoreCase("now"))
				fd.setValue(new Date());
			else {
				fd.setValue(Times.toDay());
			}
			return fd;
		} else if (name.equalsIgnoreCase("user")) {
			FieldDo fd = new FieldDo(FieldType.VARCHAR);
			fd.setName(name);
			fd.setValue(Contexts.getCommandContext().getUser().getId());
			return fd;
		} else if (name.equals("SUB")) {
			FieldDo fd = new FieldDo(FieldType.OBJECT);
			fd.setName(name);
			fd.setValue(getSub(false, false));
			return fd;
		} else if (name.equals("sub")) {
			FieldDo fd = new FieldDo(FieldType.OBJECT);
			fd.setName(name);
			fd.setValue(getSub(false, true));
			return fd;
		} else if (name.equals("SUBS")) {
			FieldDo fd = new FieldDo(FieldType.OBJECT);
			fd.setName(name);
			fd.setValue(getSub(true, false));
			return fd;
		} else if (name.equals("subs")) {
			FieldDo fd = new FieldDo(FieldType.OBJECT);
			fd.setName(name);
			fd.setValue(getSub(true, true));
			return fd;
		}
		throw new EasyPlatformWithLabelKeyException(
				"context.reserve.word.invalid", name);
	}

	private final static String[] getSub(boolean isAll, boolean self) {
		CommandContext cc = Contexts.getCommandContext();
		String orgId = cc.getUser().getOrg().getId();
		String query = cc.getProjectService().getConfig().getOrgSubQuery();
		if (Strings.isBlank(query))
			return new String[] { orgId };
		List<String> result = new ArrayList<String>();
		if (self)
			result.add(orgId);
		query(isAll, result, query, cc.getBizDao(), orgId);
		String[] data = new String[result.size()];
		result.toArray(data);
		return data;
	}

	public final static void query(boolean isAll, List<String> result,
			String query, BizDao dao, String org) {
		List<FieldDo> params = new ArrayList<FieldDo>();
		int count = StringUtils.countMatches(query, "?");
		for (int i = 0; i < count; i++)
			params.add(new FieldDo(FieldType.VARCHAR, org));
		List<FieldDo[]> data = dao.selectList(query, params);
		if (!data.isEmpty()) {
			for (FieldDo[] fvs : data) {
				String orgId = (String) fvs[0].getValue();
				if (!result.contains(orgId)) {// 避免死循环
					result.add(orgId);
					if (isAll)
						query(isAll, result, query, dao, orgId);
				}//if
			}//for
		}//if
	}
}
